#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>

#define MAX_BUF_SIZE 1024

int main(int argc, char const *argv[])
{   
    int sockfd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t server_addr_len;
    char recv_buf[MAX_BUF_SIZE];
    char send_buf[MAX_BUF_SIZE];
    int recv_len;

    // 创建UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址信息
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8888);
    server_addr.sin_addr.s_addr = inet_addr("192.168.13.66");

    bind(sockfd, (struct sockaddr*)&client_addr, sizeof(client_addr));

    // 循环接收和发送数据
    while (1) {
        memset(recv_buf, 0, MAX_BUF_SIZE);
        memset(send_buf, 0, MAX_BUF_SIZE);

        // 接收数据
        //读控制台里的数据写入send_buf
        read(STDIN_FILENO, send_buf, MAX_BUF_SIZE);
        sendto(sockfd, send_buf, strlen(send_buf), 0, (struct sockaddr*)&server_addr, sizeof(server_addr));
        // 判断接收到的数据是否为EOF
        recvfrom(sockfd, recv_buf, MAX_BUF_SIZE, 0, (struct sockaddr*)&server_addr, &server_addr_len);

        if (strcmp(recv_buf, "exit") == 0) {
            printf("Received EOF from server. Exiting.\n");
            break;
        }

        printf("Received from server: %s\n", recv_buf);
    }

    printf("Client exit\n");
    close(sockfd);
    return 0;
}
